package woaini.fenger.core.dispatcher.impl;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import woaini.fenger.core.bind.domain.BotBind;
import woaini.fenger.core.bind.service.BotUserService;
import woaini.fenger.core.bot.enums.PLatFormEnum;
import woaini.fenger.core.bot.event.MessageSender;
import woaini.fenger.core.bot.event.message.GroupMessageEvent;
import woaini.fenger.core.bot.id.ID;
import woaini.fenger.core.bot.session.Session;
import woaini.fenger.core.dispatcher.IBotInterceptor;

/**
 * 用户绑定拦截器
 *
 * @see woaini.fenger.core.dispatcher.impl.UserBindInterceptor
 * @author yefeng {@code @Date} 2023-05-16 16:50:39
 */
@Component
@AllArgsConstructor
public class UserBindInterceptor implements IBotInterceptor {

    private BotUserService botUserService;

    @Override
    public boolean dispatch(Session session) {

        //判断消息发送的
        MessageSender sender = session.getEvent().getSender();
        //群聊必须at
        if (session.getEvent() instanceof GroupMessageEvent groupMessageEvent){
            if (!groupMessageEvent.getMessage().isAt(session.getBot().getSelfId())){
                return true;
            }
        }
        ID userId = sender.getUserId();
        PLatFormEnum pLatForm = session.getBot().getPLatForm();
        String name = sender.getName();
        String nickname = sender.getNickname();
        BotBind botBind = botUserService.saveOrUpdate(userId, pLatForm, name, nickname);
        session.setBind(botBind);
        return IBotInterceptor.super.dispatch(session);
    }

    @Override
    public int order() {
        return CmdInterceptor.ORDER - 1;
    }
}
